package com.zhupanlin.zhyl.msm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.zhupanlin.zhyl.common.exception.Zhylxception;
import com.zhupanlin.zhyl.common.result.ResultCodeEnum;
import com.zhupanlin.zhyl.common.utils.RandomUtil;
import com.zhupanlin.zhyl.msm.service.MsmService;
import com.zhupanlin.zhyl.msm.utils.ConstantPropertiesUtils;
import com.zhupanlin.zhyl.vo.msm.MsmVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/12/1 15:11
 */
@Service
public class MsmServiceImpl implements MsmService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送手机验证码
     *
     * @param phone
     */
    @Override
    public boolean sendCode(String phone) {
        if (StringUtils.isEmpty(phone)) {
            return false;
        }
        // 从 redis 获取验证码，如果能够获取到，直接返回
        // 手机号为 key
        String code = stringRedisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            throw new Zhylxception("验证码已发送，请稍后重试", 200);
        }

        // 如果获取不到
        // 生成验证码，进行发送
        code = RandomUtil.getSixBitRandom();


        return send(phone, code);
    }

    private boolean send(String phone, String code) {
        //整合阿里云短信服务
        //设置相关参数
        DefaultProfile profile = DefaultProfile.
                getProfile(ConstantPropertiesUtils.REGION_ID,
                        ConstantPropertiesUtils.ACCESS_KEY_ID,
                        ConstantPropertiesUtils.SECRET);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        //手机号
        request.putQueryParameter("PhoneNumbers", phone);
        //签名名称
        request.putQueryParameter("SignName", "湖工智慧医疗系统");
        //模板code
        request.putQueryParameter("TemplateCode", "SMS_475835824");
        //验证码  使用json格式   {"code":"123456"}
        Map<String,Object> param = new HashMap();
        param.put("code",code);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        //调用方法进行短信发送
        try {
            CommonResponse response = client.getCommonResponse(request);
            // 生成验证码存入 redis 中，设置有效时间
            stringRedisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * MQ 使用发送短信
     *
     * @param msmVo
     */
    @Override
    public boolean send(MsmVo msmVo) {
        if (!StringUtils.isEmpty(msmVo.getPhone())) {
            String code = (String) msmVo.getParam().get("code");
            boolean isSend = send(msmVo.getPhone(), msmVo.getParam());
            return isSend;
        }
        return false;
    }

    private boolean send(String phone, Map<String, Object> param) {
        //整合阿里云短信服务
        //设置相关参数
        DefaultProfile profile = DefaultProfile.
                getProfile(ConstantPropertiesUtils.REGION_ID,
                        ConstantPropertiesUtils.ACCESS_KEY_ID,
                        ConstantPropertiesUtils.SECRET);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        //手机号
        request.putQueryParameter("PhoneNumbers", phone);
        //签名名称
        request.putQueryParameter("SignName", "湖工智慧医疗系统");
        //模板code
        request.putQueryParameter("TemplateCode", "SMS_475835824");
        //验证码  使用json格式   {"code":"123456"}
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        //调用方法进行短信发送
        try {
            CommonResponse response = client.getCommonResponse(request);
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
